<?php

namespace app\api\model\shop;


use app\shopapi\model\ShopGoods;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
use think\Cache;

class ShopOrderCreate extends Model
{


    // 订单待付款
    const ORDER_CREATE = 0;

    // 订单已支付
    //const ORDER_PAY = 1;

    // 订单待使用
    const ORDER_VERIFY = 2;

    // 订单已完成
    const ORDER_COMPLETE = 3;
    // 订单已关闭
    const ORDER_CLOSE = -1;
    /**
     * 基础订单状态(不同类型的订单可以不使用这些状态，但是不能冲突)
     * @var unknown
     */
    public $order_status = [
        self::ORDER_CREATE => [
            'status' => self::ORDER_CREATE,
            'name' => '待支付',
        ],
        self::ORDER_VERIFY => [
            'status' => self::ORDER_VERIFY,
            'name' => '待使用',
        ],
        self::ORDER_COMPLETE => [
            'status' => self::ORDER_COMPLETE,
            'name' => '已完成',
        ],
        self::ORDER_CLOSE => [
            'status' => self::ORDER_CLOSE,
            'name' => '已关闭',
        ],

    ];
    /**
     * 基础支付方式(不考虑实际在线支付方式或者货到付款方式)
     * @var unknown
     */
    public $pay_type = [
        'WECHAT_PAY' => '微信支付',
        'ALIPAY' => '支付宝支付',
    ];


    //创建订单
    public function createOrder($params)
    {
        $calculate_data = $this->calculate($params);

        Db::startTrans();

        try {
            $order_model = new ShopOrder();

            $order_no = $this->createOrderNo($calculate_data['goods_info']['shop_id'],$params['user_id']);

            $data = [
                'user_id'=>$params['user_id'],
                'shop_id'=>$calculate_data['goods_info']['shop_id'],
                'order_status_name'=>$this->order_status[0]['name'],
                'goods_id'=>$calculate_data['goods_info']['goods_id'],
                'goods_name'=>$calculate_data['goods_info']['goods_name'],
                'goods_img'=>$calculate_data['goods_info']['images'],
                'goods_price'=>$calculate_data['goods_info']['price'],
                'order_no'=>$order_no,
                'order_price'=>$calculate_data['order_price'],
                'rebate'=>$calculate_data['rebate'],
                'closetime'  => time() + 30*60,
                'may_use_time_type'=>$calculate_data['goods_info']['may_use_time_type'],
                'use_time_type'=>$calculate_data['goods_info']['use_time_type'],
                'coupon_limited'=>$calculate_data['goods_info']['coupon_limited'],
                'other_rule'=>$calculate_data['goods_info']['other_rule'],
                'use_date'=>$calculate_data['goods_info']['use_date'],
            ];
            if ($data['may_use_time_type']==1){
                $data['may_use_time_day'] = $calculate_data['goods_info']['may_use_time_day'];
                //$data['start_may_use_time'] = time();
                //$data['end_may_use_time'] = $calculate_data['goods_info']['may_use_time_day']*86400;
            } else {
                $data['start_may_use_time'] = $calculate_data['goods_info']['start_may_use_time'];
                $data['end_may_use_time'] = $calculate_data['goods_info']['end_may_use_time'];
            }
            if ($data['use_time_type']==1){
                $data['start_use_time'] = $calculate_data['goods_info']['start_use_time'];
                $data['end_use_time'] = $calculate_data['goods_info']['end_use_time'];
            }
            if ($data['coupon_limited']!=0){
                $data['limited_num'] = $calculate_data['goods_info']['limited_num'];
            }

            $res =  $order_model->save($data);

            if ($res){
                Db::commit();
                return $order_model;
            } else {
                Db::rollback();
                throw new \Exception('提交失败');
            }
        }  catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    public function getUseDate()
    {
        return [1=>'周一',2=>'周二',3=>'周三',4=>'周四',5=>'周五',6=>'周六',0=>'周日',7=>'节假日通用',8=>'节假日不可用'];
    }

    public function hasDuplicates($array1, $array2) {
        $diff = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));
        return !empty($diff);
    }

    //转换商品的可用日期
    public function getGoodsUseDate($week)
    {
        $week = explode(',',$week);
        $week_list = [0,1,2,3,4,5,6,7,8];

        $res = $this->hasDuplicates($week,$week_list);
        $week_list = $this->getUseDate();
        if ($res){

            $work_week = [];
            foreach ($week as $k=>$v){
                array_push($work_week,$week_list[$v]);
            }
            return implode(',',$work_week);
        } else {
            return '周一至周日';
        }
    }

    //提交页预览信息
    public function calculate($params)
    {
        $user_id = $params['user_id'];
        $goods_info = ShopGoods::alias('sg')
            ->join('shop s','sg.shop_id = s.shop_id')
            ->where(['sg.goods_id'=>$params['goods_id']])
            ->field('sg.goods_id,sg.shop_id,sg.goods_name,sg.images,sg.price,sg.commission_rate,sg.goods_state,sg.may_use_time_type,
            sg.start_may_use_time,sg.end_may_use_time,sg.may_use_time_day,sg.use_people_type,sg.start_use_people,sg.end_use_people,
            sg.use_time_type,sg.start_use_time,sg.end_use_time,sg.coupon_limited,sg.limited_num,sg.other_rule,sg.stock_type,sg.sale,
            sg.stock,sg.every_stock_type,sg.every_stock,sg.everyone_everyday_buy_type,sg.everyone_everyday_buy,s.shop_name,sg.use_date,sg.use_date_type')
            ->find();
        if ($goods_info['goods_state']!=1)throw new \Exception('该团购已下架');
        if ($goods_info['use_date_type']==1){
            $goods_info['use_date'] = $this->getGoodsUseDate($goods_info['use_date']);
        } else {
            $goods_info['use_date'] = '所有日期可用';
        }
        //库存类型,1限制最多
        if ($goods_info['stock_type']==1){
            if ($goods_info['sale']>=$goods_info['stock']){
                throw new \Exception('该团购暂无库存');
            }
        }
        //每日库存类型,1限制最多
        if ($goods_info['every_stock_type']==1){
            $today_sale = ShopOrder::where(['goods_id'=>$goods_info['goods_id'],'pay_status'=>1])->count();
            if ($today_sale>=$goods_info['every_stock'])throw new \Exception('当天库存已售完');
        }
        //每人每日最多购买类型,1限制最多
        if ($goods_info['everyone_everyday_buy_type']==1){
            $today_sale = ShopOrder::where(['goods_id'=>$goods_info['goods_id'],'pay_status'=>1,'user_id'=>$user_id])->count();
            if ($today_sale>=$goods_info['everyone_everyday_buy'])throw new \Exception('已达到每人每日购买上限');
        }
        $rebate = $this->goods_rebate($goods_info['price'],$goods_info['commission_rate']);
        $order_price = $goods_info['price'];
        $data = [
            'goods_info'=>$goods_info,
            'rebate'=>$rebate,
            'order_price'=>$order_price
        ];
        return $data;
    }

    //计算团购返利
    public function goods_rebate($price,$commission_rate)
    {
        $rebate = $price*$commission_rate/100*0.4;

        return round($rebate,2);
    }

    /**
     * 生成订单编号
     *
     * @param array $site_id
     */
    public function createOrderNo($shop_id, $user_id = 0)
    {
        $time_str = date('YmdHi');
        $max_no = Cache::get($shop_id . "_" . $user_id . "_" . $time_str);
        if (!isset($max_no) || empty($max_no)) {
            $max_no = 1;
        } else {
            $max_no = $max_no + 1;
        }
        $order_no = $time_str . $user_id . sprintf("%03d", $max_no);
        Cache::set($shop_id . "_" . $user_id . "_" . $time_str, $max_no);
        return $order_no;
    }



}